package org.sunshine.mamadu.Listeners;

import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.sunshine.mamadu.Advertisement;
import org.sunshine.mamadu.Commons;
import org.sunshine.mamadu.LocalLogger;
import org.sunshine.mamadu.MamaduCheck;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

public class SendMailListener implements MamaduCheck.Listener{

    private static String mailConfigPath = "mail.properties";

    private Properties mailProperties;

    private List<Recepient> recepients;

    private String mailHost;
    private String mailLogin;
    private String mailPassword;

    public static void setMailConfigPath(String mailConfigPath) {
        SendMailListener.mailConfigPath = mailConfigPath;
    }


    public void init() throws IOException {
        if (mailProperties == null) {
            InputStream inputStream = Commons.getFile(mailConfigPath);
            mailProperties = new Properties();
            mailProperties.load(inputStream);
            recepients = new ArrayList<Recepient>();
            for (Object o : mailProperties.keySet()) {
                String key = (String) o;
                if ("mail.hostname".equals(key)) {
                    mailHost = mailProperties.getProperty(key);
                    continue;
                }

                if ("mail.login".equals(key)) {
                    mailLogin = mailProperties.getProperty(key);
                    continue;
                }

                if ("mail.password".equals(key)) {
                    mailPassword = mailProperties.getProperty(key);
                    continue;
                }

                Recepient recepient = new Recepient();

                String value = mailProperties.getProperty(key);
                String[] strings = value.split(",");
                recepient.address = strings[0];
                recepient.name = strings[1];
                recepients.add(recepient);


            }

        }

    }

    private class Recepient {
        String address;
        String name;
    }

    public void handleNewAds(final List<Advertisement> list) {
        Thread thread = new Thread(new Runnable(){
            public void run() {
                sendMail(list);
            }
        });
        thread.start();
    }

    public void handleInitAds(final List<Advertisement> list) {

    }

    private void sendMail(List<Advertisement> newAds){
        try {
            SimpleEmail email = new SimpleEmail();
            email.setCharset("utf-8");
            email.setSSL(true);
            email.setHostName(mailHost);
            email.setAuthentication(mailLogin, mailPassword);
            for (Iterator<Recepient> iterator = recepients.iterator(); iterator.hasNext();) {
                Recepient recepient = iterator.next();
                email.addTo(recepient.address, recepient.name);
            }

            email.setFrom("mamadu_checker@home.org", "me");


            StringBuilder subject = new StringBuilder();
            StringBuilder body = new StringBuilder("Новые объявления на Мамаду:\n");
            for (Iterator<Advertisement> iterator = newAds.iterator(); iterator.hasNext();) {
                Advertisement advertisement = iterator.next();
                subject.append(advertisement.getName() + "; ");

                body.append("\n");
                body.append("Name: " + advertisement.getName() + "\n");
                body.append("Phone: " + advertisement.getPhone() + "\n");
                body.append("Email: " + advertisement.getEmail() + "\n");
                body.append("Date: " + advertisement.getDate() + "\n");
                body.append("Content: " + advertisement.getContent() + "\n");

            }

            email.setSubject(subject.toString());
            email.setMsg(body.toString());
            email.send();
            LocalLogger.LOGGER.log(Level.INFO, "Main notification sended.");
        } catch (EmailException e) {
            LocalLogger.LOGGER.log(Level.INFO, "Exception during sending mail.", e);
        }

    }


    public static void sendMail(
            String to,
            String cc,
            String bcc,
            String from,
            String subject,
            String text,
            String smtpHost)
            throws Exception, NullPointerException {

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);

        if (to != null) {
            InternetAddress[] toAddrs = InternetAddress.parse(to, false);
            msg.setRecipients(Message.RecipientType.TO, toAddrs);
        } else {
            throw new NullPointerException();
        }

        if (cc != null) {
            InternetAddress[] ccAddrs = InternetAddress.parse(cc, false);
            msg.setRecipients(Message.RecipientType.CC, ccAddrs);
        }

        if (bcc != null) {
            InternetAddress[] bccAddrs = InternetAddress.parse(bcc, false);
            msg.setRecipients(Message.RecipientType.BCC, bccAddrs);
        }

        if (subject != null) {
            msg.setSubject(subject);
        }

        msg.setFrom(new InternetAddress(from));

        if (text != null) {
            msg.setText(text);
        }

        Transport.send(msg);
    }

}
